package il.technion.cs236369.dal;

import il.technion.cs236369.exceptions.NotFoundException;
import il.technion.cs236369.interfaces.ICacheEntry;
import il.technion.cs236369.interfaces.ICacheEntryDal;

import java.net.MalformedURLException;
import java.sql.SQLException;
import java.util.HashMap;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class DalTests {

	private static ICacheEntryDal	dal;
	private static ICacheEntry		basicEntry;

	// contains and clear are tested throughout

	@SuppressWarnings("serial")
	@BeforeClass
	public static void classSetup() throws ClassNotFoundException, SQLException, MalformedURLException {
		dal = new CacheEntryDalImpl("com.mysql.jdbc.Driver", "jdbc:mysql://127.0.0.1:3306/", "proxy", "cache", "root", "1234");
		basicEntry = new CacheEntryImpl("http://www.url.com", new HashMap<String, String>() {
			{
				put("header1", "header1");
				put("header2", "header2");
			}
		}, "Body".getBytes());
	}

	@Before
	public void before() throws SQLException {
		dal.clear();
	}

	@After
	public void after() throws SQLException {
		dal.clear();
	}

	@Test
	public void testStore() throws SQLException, MalformedURLException {
		Assert.assertFalse("does not exist", dal.contains(basicEntry.getURL()));
		// make sure nothing crashes
		boolean result = dal.store(basicEntry);
		Assert.assertFalse("did not exist yet", result);
		Assert.assertTrue("insertion successful", dal.contains(basicEntry.getURL()));
		result = dal.store(basicEntry);
		Assert.assertTrue("already existed", dal.store(basicEntry));
		Assert.assertTrue("second insertion successful", dal.contains(basicEntry.getURL()));
	}

	@Test(expected = NotFoundException.class)
	public void testLoadFails() throws SQLException, NotFoundException {
		dal.load(basicEntry.getURL());
	}

	@Test
	public void testLoad() throws NotFoundException, SQLException {
		dal.store(basicEntry);
		ICacheEntry savedEntry = dal.load(basicEntry.getURL());
		Assert.assertEquals("succesful load", savedEntry, basicEntry);
	}

	@Test
	public void testRemove() throws SQLException {
		Assert.assertFalse("nothing to remove", dal.remove(basicEntry.getURL()));
		dal.store(basicEntry);
		Assert.assertTrue("insertion succesful", dal.contains(basicEntry.getURL()));
		Assert.assertTrue("removal succesful", dal.remove(basicEntry.getURL()));
		Assert.assertFalse("no longer exists", dal.contains(basicEntry.getURL()));
	}
}
